//
//  OtherViewController.swift
//  EasePods
//
//  Created by 易先生 on 2024/4/7.
//

import UIKit
import RxSwift
import RxCocoa
import RxDataSources
import CRPEarPhone

class OtherViewController: ViewController {
    
    let viewModel = OtherViewModel()
    
    override func makeUI() {
        super.makeUI()
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        BluetoothManager.shared.connectState.subscribe { [weak self] state in
            guard let self = self else { return }
            if state == .connected {
                self.tableView.tableHeaderView = nil
            } else {
                self.tableView.tableHeaderView = headView
            }
        }.disposed(by: rx.disposeBag)
    }
    
    override func bindViewModel() {
        super.bindViewModel()
        
        let dataSource = RxTableViewSectionedReloadDataSource<OtherSection> { (_, tableView, _, item) in
            switch item {
            case .weatherItem(let cellModel):
                let cell = tableView.dequeueReusableCell(withIdentifier: DefaultSwitchTableViewCell.reuseIdentifier) as! DefaultSwitchTableViewCell
                cell.bind(viewModel: cellModel)
                cell.titleLabel.text = R.string.localizable.setting_weather_update_every_hour()
                return cell
            case .temperatureFormatItem(let cellModel):
                let cell = tableView.dequeueReusableCell(withIdentifier: DefaultTableViewCell.reuseIdentifier) as! DefaultTableViewCell
                cell.bind(viewModel: cellModel)
                cell.titleL.text = R.string.localizable.setting_weather_temperature_format()
                cell.detailL.text = Weather.shared.tempformat.description
                return cell
            case .locationItem(let cellModel):
                let cell = tableView.dequeueReusableCell(withIdentifier: DefaultTableViewCell.reuseIdentifier) as! DefaultTableViewCell
                cell.bind(viewModel: cellModel)
                cell.titleL.text = R.string.localizable.setting_weather_location()
                return cell
            }
        }
        viewModel.dataSource.bind(to: tableView.rx.items(dataSource: dataSource)).disposed(by: rx.disposeBag)
        tableView.rx.setDelegate(self).disposed(by: rx.disposeBag)
        
        tableView.rx.itemSelected.subscribe(onNext: { [weak self] indexPath in
            if indexPath.row == 1 {
                let view = CustomPickerPopView()
                let defaultIndex = Weather.shared.tempformat == .degreeCelsius ? 0 : 1
                view.bind(to: [TemperatureType.degreeCelsius.description, TemperatureType.fahrenheit.description], title: R.string.localizable.setting_weather_temperature_format(), selectIndex: defaultIndex)
                view.confirmBlock = { [weak self] selectIndex in
                    UIView.dismissSheet()
                    let type = selectIndex == 0 ? TemperatureType.degreeCelsius : TemperatureType.fahrenheit
                    Weather.shared.tempformat = type
                    self?.tableView.reloadRows(at: [indexPath], with: .none)
                }
                UIView.showSheet(with: view)
            }
            
            if indexPath.row == 2 {
                if getCurrentLanguage() == "cn" {
                    let vc = OtherCityViewController()
                    self?.navigationController?.pushViewController(vc, animated: true)
                } else {
                    let vc = OtherSearchCityViewController()
                    vc.modalPresentationStyle = .fullScreen
                    self?.present(vc, animated: true, completion: nil)
                }
            }
        }).disposed(by: rx.disposeBag)
    }
    
    lazy var headView: UnBoundTopTipsView = {
        let view = UnBoundTopTipsView()
        return view
    }()

    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.backgroundColor = R.color.common_10_bg_page()
        tableView.estimatedRowHeight = 70
        tableView.sectionFooterHeight = 0
        tableView.rowHeight = UITableView.automaticDimension
        tableView.separatorStyle = .singleLine
        tableView.separatorColor = R.color.common_6_line()
        tableView.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        tableView.register(DefaultTableViewCell.self, forCellReuseIdentifier: DefaultTableViewCell.reuseIdentifier)
        tableView.register(DefaultSwitchTableViewCell.self, forCellReuseIdentifier: DefaultSwitchTableViewCell.reuseIdentifier)
        return tableView
    }()
}

extension OtherViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 40
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let sectionView = View(frame: CGRect(x: 0, y: 0, width: view.bounds.size.width, height: 40))
        sectionView.backgroundColor = R.color.common_10_bg_page()
        let titleLabel = Label(frame: CGRect(x: 20, y: 0, width: view.bounds.size.width - 40, height: 40))
        titleLabel.text = R.string.localizable.setting_weather_title()
        titleLabel.textColor = R.color.common_3_text()
        titleLabel.font = Fonts.systemFont(ofSize: 12)
        sectionView.addSubview(titleLabel)
        return sectionView
    }
}

extension TemperatureType : CustomStringConvertible {
    public var description: String {
        switch self {
        case .degreeCelsius: return R.string.localizable.common_unit_degree_celsius()
        case .fahrenheit: return R.string.localizable.common_unit_fahrenheit()
        }
    }
}
